const express = require('express');
const router = express.Router();
const { pool } = require('../config/database');

// 获取订单列表
router.get('/list', async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      order_status, 
      user_id,
      start_date,
      end_date 
    } = req.query;
    
    const offset = (page - 1) * limit;
    
    let whereClause = 'WHERE o.is_deleted = 0';
    let params = [];
    
    if (order_status !== undefined) {
      whereClause += ' AND o.order_status = ?';
      params.push(order_status);
    }
    
    if (user_id) {
      whereClause += ' AND o.user_id = ?';
      params.push(user_id);
    }
    
    if (start_date) {
      whereClause += ' AND o.create_time >= ?';
      params.push(start_date);
    }
    
    if (end_date) {
      whereClause += ' AND o.create_time <= ?';
      params.push(end_date);
    }
    
    const [orders] = await pool.execute(
      `SELECT o.*, 
              (SELECT COUNT(*) FROM order_item oi WHERE oi.order_id = o.id) as item_count
       FROM order_info o 
       ${whereClause} 
       ORDER BY o.create_time DESC 
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), parseInt(offset)]
    );
    
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM order_info o ${whereClause}`,
      params
    );
    
    res.json({
      success: true,
      message: '获取订单列表成功',
      data: {
        list: orders,
        total: countResult[0].total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败',
      error: error.message
    });
  }
});

// 根据ID获取订单详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取订单基本信息
    const [orderRows] = await pool.execute(
      'SELECT * FROM order_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (orderRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 获取订单项
    const [itemRows] = await pool.execute(
      'SELECT * FROM order_item WHERE order_id = ? AND is_deleted = 0',
      [id]
    );
    
    res.json({
      success: true,
      message: '获取订单详情成功',
      data: {
        order: orderRows[0],
        items: itemRows
      }
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败',
      error: error.message
    });
  }
});

// 创建订单
router.post('/create', async (req, res) => {
  const connection = await pool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    const {
      user_id,
      nick_name,
      coupon_id,
      total_amount,
      coupon_amount = 0,
      original_total_amount,
      feight_fee = 0,
      pay_type,
      receiver_name,
      receiver_phone,
      receiver_tag_name,
      receiver_province,
      receiver_city,
      receiver_district,
      receiver_address,
      remark,
      items
    } = req.body;
    
    if (!user_id || !total_amount || !receiver_name || !receiver_phone || !receiver_address) {
      throw new Error('必填字段不能为空');
    }
    
    if (!items || items.length === 0) {
      throw new Error('订单项不能为空');
    }
    
    // 生成订单号
    const order_no = 'ORD' + Date.now() + Math.floor(Math.random() * 1000);
    
    // 插入订单主表
    const [orderResult] = await connection.execute(
      `INSERT INTO order_info (
        user_id, nick_name, order_no, coupon_id, total_amount, coupon_amount,
        original_total_amount, feight_fee, pay_type, order_status,
        receiver_name, receiver_phone, receiver_tag_name, receiver_province,
        receiver_city, receiver_district, receiver_address, remark
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        user_id, nick_name, order_no, coupon_id, total_amount, coupon_amount,
        original_total_amount, feight_fee, pay_type,
        receiver_name, receiver_phone, receiver_tag_name, receiver_province,
        receiver_city, receiver_district, receiver_address, remark
      ]
    );
    
    const order_id = orderResult.insertId;
    
    // 插入订单项
    for (const item of items) {
      await connection.execute(
        `INSERT INTO order_item (
          order_id, sku_id, sku_name, thumb_img, sku_price, sku_num
        ) VALUES (?, ?, ?, ?, ?, ?)`,
        [
          order_id, item.sku_id, item.sku_name, item.thumb_img,
          item.sku_price, item.sku_num
        ]
      );
    }
    
    await connection.commit();
    
    res.json({
      success: true,
      message: '创建订单成功',
      data: {
        order_id,
        order_no,
        total_amount
      }
    });
  } catch (error) {
    await connection.rollback();
    console.error('创建订单失败:', error);
    res.status(500).json({
      success: false,
      message: '创建订单失败',
      error: error.message
    });
  } finally {
    connection.release();
  }
});

// 更新订单状态
router.put('/status/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { order_status } = req.body;
    
    if (order_status === undefined) {
      return res.status(400).json({
        success: false,
        message: '订单状态不能为空'
      });
    }
    
    const [existingOrder] = await pool.execute(
      'SELECT * FROM order_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingOrder.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 根据状态更新相应的时间字段
    let updateFields = 'order_status = ?';
    let params = [order_status, id];
    
    switch (order_status) {
      case 1: // 待发货（已付款）
        updateFields += ', payment_time = NOW()';
        break;
      case 2: // 已发货
        updateFields += ', delivery_time = NOW()';
        break;
      case 3: // 已完成
        updateFields += ', receive_time = NOW()';
        break;
      case -1: // 已取消
        updateFields += ', cancel_time = NOW()';
        break;
    }
    
    await pool.execute(
      `UPDATE order_info SET ${updateFields} WHERE id = ?`,
      params
    );
    
    res.json({
      success: true,
      message: '更新订单状态成功'
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败',
      error: error.message
    });
  }
});

// 取消订单
router.put('/cancel/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { cancel_reason } = req.body;
    
    const [existingOrder] = await pool.execute(
      'SELECT * FROM order_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingOrder.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    if (existingOrder[0].order_status !== 0) {
      return res.status(400).json({
        success: false,
        message: '只有待付款的订单才能取消'
      });
    }
    
    await pool.execute(
      'UPDATE order_info SET order_status = -1, cancel_time = NOW(), cancel_reason = ? WHERE id = ?',
      [cancel_reason, id]
    );
    
    res.json({
      success: true,
      message: '取消订单成功'
    });
  } catch (error) {
    console.error('取消订单失败:', error);
    res.status(500).json({
      success: false,
      message: '取消订单失败',
      error: error.message
    });
  }
});

// 删除订单（软删除）
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const [existingOrder] = await pool.execute(
      'SELECT * FROM order_info WHERE id = ? AND is_deleted = 0',
      [id]
    );
    
    if (existingOrder.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    await pool.execute(
      'UPDATE order_info SET is_deleted = 1 WHERE id = ?',
      [id]
    );
    
    res.json({
      success: true,
      message: '删除订单成功'
    });
  } catch (error) {
    console.error('删除订单失败:', error);
    res.status(500).json({
      success: false,
      message: '删除订单失败',
      error: error.message
    });
  }
});

// 获取订单统计信息
router.get('/stats', async (req, res) => {
  try {
    const [statusStats] = await pool.execute(
      `SELECT order_status, COUNT(*) as count 
       FROM order_info 
       WHERE is_deleted = 0 
       GROUP BY order_status`
    );
    
    const [totalStats] = await pool.execute(
      `SELECT 
        COUNT(*) as total_orders,
        SUM(total_amount) as total_amount,
        SUM(CASE WHEN order_status = 3 THEN total_amount ELSE 0 END) as completed_amount
       FROM order_info 
       WHERE is_deleted = 0`
    );
    
    res.json({
      success: true,
      message: '获取订单统计成功',
      data: {
        statusStats,
        totalStats: totalStats[0]
      }
    });
  } catch (error) {
    console.error('获取订单统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单统计失败',
      error: error.message
    });
  }
});

module.exports = router;